package com.luckdraw.service.game;

import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.nutz.ioc.Ioc;

import com.luckdraw.domain.Activity;
import com.luckdraw.service.GamePool;
import com.luckdraw.service.GameService;

/**
 * 活动奖池生成线程
 * @ClassName: GameRunnable 
 * @author gaotaochen
 * @Description: 
 * @date 2017年1月18日 下午4:00:36 
 *
 */
public class GameRunnable implements Runnable,RefreshDataCallBack{
	
	private int setId;
	
	private Ioc ioc;
	
	private Activity set;
	
	private GamePoolCallBack callBack;
	
	public GameRunnable(Ioc ioc,int setId,GamePoolCallBack callBack){
		this.ioc = ioc;
		this.setId = setId;
		this.callBack = callBack;
	}
	
	public void invoke(Activity act) {
		this.set = act;
	}

	public void run() {
		Dao dao = ioc.get(Dao.class);
		set = dao.fetch(Activity.class, Cnd.where("id", "=", setId).and("status", "=", 1));
		new Thread(new RefreshDataRunnable(ioc, setId, this)).start();
		GamePool gamePool = (GamePool)ioc.get(GameService.class);
		while(set!=null){
			Game game = new Game(set.getSize(), set.getProfitable(), set.getCost(), 1d-set.getCommissionRate(), set.getMinimumReturnRatio(), set.getMaximumYieldRatio());
			game.initRewardList();
			//向活动池中添加活动
			gamePool.put(set.getId(), game);
		}
		//通知主线程本轮活动结束
		callBack.callBack(setId);
	}
}

/**
 * 数据刷新回调接口
 * @author
 *
 */
interface RefreshDataCallBack{
	public void invoke(Activity act);
}
/**
 * 数据刷新线程
 * @author 
 *
 */
class RefreshDataRunnable implements Runnable{
	
	private Ioc ioc;
	
	private int setId;
	
	private RefreshDataCallBack callBack;
	
	public RefreshDataRunnable(Ioc ioc,int setId,RefreshDataCallBack callBack){
		this.ioc = ioc;
		this.setId = setId;
		this.callBack = callBack;
	}

	public void run() {
		Dao dao = ioc.get(Dao.class);
		//1分钟给主线程刷一次数据
		while(true){
			Activity set = dao.fetch(Activity.class, Cnd.where("id", "=", setId).and("status", "=", 1));
			callBack.invoke(set);
			try {
				Thread.sleep(60000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
	
}